// pages/personal/company/company.js
const app = getApp()
const router = require('../../../config').router;
const uploadImage = require('../../../config').uploadImage;

Page({

  /**  
   * 页面的初始数据  
   */
  data: {
    Ename: [],
    list:[],
    index: 0,
    Cname: ['市级', '省级', '国家级'],
    index1: 0,
    image: '',
    type:true,
    region: ['江苏省', '南京市', '鼓楼区'],
    customItem: '全部',
    checkbox1:false,
    model:false,
    products:[],
    Pname:'',
    Pmsg:'',
    id:'',
    edit:false
  },
  /**  
   * 生命周期函数--监听页面加载  
   */
  onLoad: function (options) {
    var that = this
    var contactName = wx.getStorageSync('contactName')
    var contactPassword = wx.getStorageSync('contactPassword')
    if (contactName != '' && contactPassword != '') {
      that.setData({
        type:false
      });
    }
    wx.request({
      url: router,
      //url:'http://47.107.80.250:18082/mobile/router',
      data: {
          appKey: 'w4q897jgvxkb',
          method: 'query.exhibition.open',
          v: '1.0',
          format: 'json',
      },
      success: function(res) {
          if (res.statusCode == 200 && res.data.error != 'error') {
              console.log(res.data.article)
              var arr = []
              for(var i=0;i<res.data.article.length;i++){
                  arr.push(res.data.article[i].title)
              }
              that.setData({
                  list: res.data.article,
                  Ename: arr
              })
          }
      }
    });
  },
  /**
   * 上传图片
   */
  uploadClick: function() {
    var that = this;
    wx.chooseImage({
      count: 1, //最多可以选择的图片总数
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        //启动上传等待中...
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 10000
        })
        var uploadImgCount = 0;
        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          wx.uploadFile({
            //url: 'http://47.107.80.250:18082/mobile/file/uploadImage',
            url:uploadImage,
            filePath: tempFilePaths[i],
            name: 'photoFile',
            formData: {
                'imgIndex': i
            },
            header: {
                "Content-Type": "multipart/form-data"
            },
            success: function(res) {
                uploadImgCount++;
                var data = res.data;
                console.log(data)
                that.setData({
                    image: data
                });
                console.log(that.data.image)
                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                    wx.hideToast();
                }
            },
            fail: function(res) {
              console.log(res)
              wx.hideToast();
              wx.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false,
                success: function(res) {}
              })
              }
            });
          }
        }
    });
  },
  //选择展会名称
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
        index: e.detail.value
    })
  },
  //选择省市区
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
        region: e.detail.value
    })
  },
  //是否龙头企业
  checkbox1Change: function (e) {
    var that = this
    console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.detail.value != ''){
      that.setData({
        checkbox1: true
      })
    }else{
        that.setData({
            checkbox1: false
        })
    }
  },
  //是否拥有无公害、绿色、有机食品认证
  checkbox2Change: function (e) {
    var that = this
    console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.detail.value != ''){
      that.setData({
         checkbox2: true
      })
    }
  },
  //选择龙头企业
  bindPicker1Change: function(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
          index1: e.detail.value
      })
  },
  //添加产品
  addClick:function(){
      var that = this
      that.setData({
          model: true
      })
  },
    closeClick:function(){
        var that = this
        that.setData({
            model: false
        })
    },
    bindWordLimit:function(e){
        var val = e.detail.value
        this.setData({
            userInput: val
        })
    },
  formSubmit1:function(e){
      console.log(e)
      var that = this;
      if(that.data.edit){
          var Pname = e.detail.value.Pname;//产品名称
          var obj = {};
          if (Pname == '') {
              wx.showModal({
                  title: '提示',
                  content: '请输入产品名称！',
                  success: function(res) {}
              })
              return
          }
          var Pmsg = e.detail.value.Pmsg;//获奖信息
          if (Pmsg == '') {
              wx.showModal({
                  title: '提示',
                  content: '请输入获奖信息！',
                  success: function(res) {}
              })
              return
          }
          var image = that.data.image;//获奖信息
          if (image == '') {
              image = that.data.product[that.data.id].url
          }
          obj.name = Pname
          obj.url = image
          obj.info = Pmsg
          that.data.products.splice(that.data.id,1,obj);
          that.setData({
              products: that.data.products,
              image:'',
              Pname:'',
              Pmsg:'',
              model:false,
              edit:false
          })
      }else{
          var Pname = e.detail.value.Pname;//产品名称
          var obj = {};
          if (Pname == '') {
              wx.showModal({
                  title: '提示',
                  content: '请输入产品名称！',
                  success: function(res) {}
              })
              return
          }
          var Pmsg = e.detail.value.Pmsg;//获奖信息
          if (Pmsg == '') {
              wx.showModal({
                  title: '提示',
                  content: '请输入获奖信息！',
                  success: function(res) {}
              })
              return
          }
          var image = that.data.image;//获奖信息
          if (image == '') {
              wx.showModal({
                  title: '提示',
                  content: '请添加产品图片！',
                  success: function(res) {}
              })
              return
          }
          obj.name = Pname
          obj.url = image
          obj.info = Pmsg
          that.data.products.push(obj)
          that.setData({
              products: that.data.products,
              image:'',
              Pname:'',
              Pmsg:'',
              model:false,
              edit:false
          })
      }
  },
  editProduct:function(e){
      console.log(e)
      var that = this
      var index = e.currentTarget.dataset.index;
      var list = that.data.products[index];
      that.setData({
          image:list.url,
          Pname:list.name,
          Pmsg:list.info,
          model:true,
          id:index,
          edit:true
      })
  },
  delProduct:function(e){
      console.log(e)
      var that = this
      var index = e.currentTarget.dataset.index
      wx.showModal({
          title: '删除产品',
          content: '确定要删除该产品？',
          showCancel: true, //是否显示取消按钮
          cancelText: "否", //默认是“取消”
          cancelColor: '', //取消文字的颜色
          confirmText: "是", //默认是“确定”
          confirmColor: '', //确定文字的颜色
          success: function(res) {
              if (res.cancel) {
                  //点击取消,默认隐藏弹框
              } else {
                  //点击确定
                  that.data.products.splice(index, 1),
                  that.setData({
                      products: that.data.products
                  })
              }
          },
          fail: function(res) {}, //接口调用失败的回调函数
          complete: function(res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
      })
  },
  formSubmit: function (e) {
    var that = this
    console.log(e)
    var exhibitorsName = that.data.list[that.data.index].title;//展会名称
    var exhibitorsId = that.data.list[that.data.index].id;//展会id
    var enterprisesName = e.detail.value.Cname;//企业名称
    if (enterprisesName == '') {
      wx.showModal({
          title: '提示',
          content: '请输入企业名称！',
          success: function(res) {}
      })
      return
    }
    var region = that.data.region[0]+that.data.region[1]+that.data.region[2];//省市区
    console.log(region)
    var address = e.detail.value.address;//企业地址
    if (address == '') {
      wx.showModal({
          title: '提示',
          content: '请输入详细地址！',
          success: function(res) {}
      })
      return
    }
    var contact = e.detail.value.name;//联系人
    if (contact == '') {
      wx.showModal({
          title: '提示',
          content: '请输入联系人姓名！',
          success: function(res) {}
      })
      return
    }
    var phone = e.detail.value.phone;
    if (phone == '') {
      wx.showModal({
          title: '提示',
          content: '请输入联系人电话！',
          success: function(res) {}
      })
      return
    }
    var introduction = e.detail.value.report;//企业简介
    if (introduction == '') {
      wx.showModal({
          title: '提示',
          content: '请输入简介（1000字以内）！',
          success: function(res) {}
      })
      return
    }
    var isEnterprises = '';//是否为龙头企业（0.否 1.是）
    var enterprisesType = '';//龙头企业性质
    if(that.data.checkbox1){
      isEnterprises = 1
      enterprisesType = that.data.Cname[that.data.index1];
    }else{
      isEnterprises = 0
    }
    var enterprisesCode = e.detail.value.Ucode;//统一社会信用代码
    if (enterprisesCode == '') {
      wx.showModal({
          title: '提示',
          content: '请输入统一社会信用代码！',
          success: function(res) {}
      })
      return
    }
    var foodCode = e.detail.value.number1;//食品流通许可证号
    if (foodCode == '') {
      wx.showModal({
          title: '提示',
          content: '请输入食品流通许可证号！',
          success: function(res) {}
      })
      return
    }
    var produceCode = e.detail.value.number2;//食品生产许可证号
    if (produceCode == '') {
      wx.showModal({
          title: '提示',
          content: '请输入食品生产许可证号！',
          success: function(res) {}
      })
      return
    }
    var organicFood = '';//是否拥有无公害、绿色、有机食品认证（0.否 1.是）
    if(that.data.checkbox2){
      organicFood = 1
    }else{
      organicFood = 0
    }
    var commercePlatform = e.detail.value.URL;//企业现有电商平台
    if (commercePlatform == '') {
      wx.showModal({
          title: '提示',
          content: '请输入店铺链接！',
          success: function(res) {}
      })
      return
    }

    var productName = JSON.stringify(that.data.products)
    console.log(productName)


    wx.request({
        url: router,
        //url:'http://47.107.80.250:18082/mobile/router',
        data: {
          appKey: 'w4q897jgvxkb',
          method: 'contact.exhibitors.add',
          v: '1.0',
          format: 'json',
            exhibitorsId:exhibitorsId,
            exhibitorsName:exhibitorsName,
            // province:'省份id',
            // city:'城市id',
            // country:'区域id',
            province:that.data.region[0],
            city:that.data.region[1],
            country:that.data.region[2],
            enterprisesName:enterprisesName,
            address:address,
            contact:contact,
            tel:phone,
            introduction:introduction,
            isEnterprises:isEnterprises,
            enterprisesType:enterprisesType,
            enterprisesCode:enterprisesCode,
            foodCode:foodCode,
            produceCode:produceCode,
            organicFood:organicFood,
            commercePlatform:commercePlatform,
            productName:productName
        },
        method:"POST",
        header: {
            'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.statusCode == 200 && res.data.error != 'error') {
            if(res.data.code == '200'){
                wx.showModal({
                    title: '提示',
                    content: '提交成功！',
                    success: function(res) {
                        wx.switchTab({
                            url: '/pages/personal/personal'
                        })
                    }
                })
            }else{
                wx.showModal({
                    title: '提示',
                    content: '提交失败！',
                    success: function(res) {
                        wx.switchTab({
                            url: '/pages/personal/personal'
                        })
                    }
                })
            }
          }
        }
    });
  }
})